<template>
  <div class="job-list-page-wrapper">
    <!-- 顶部导航栏 -->
    <HomeNavBar />
    
    <div class="job-list-page-container">
      <!-- 搜索栏 -->
      <el-card class="search-card" shadow="never">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索岗位名称、公司名称、描述等"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="categoryFilter" placeholder="岗位分类" clearable @change="handleFilter">
              <el-option label="全部" value="all" />
              <el-option label="技术开发" value="tech" />
              <el-option label="产品管理" value="product" />
              <el-option label="设计" value="design" />
              <el-option label="运营" value="operation" />
              <el-option label="市场销售" value="sales" />
              <el-option label="人事行政" value="hr" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="locationFilter" placeholder="工作地点" clearable @change="handleFilter">
              <el-option label="全部" value="all" />
              <el-option label="北京" value="北京" />
              <el-option label="上海" value="上海" />
              <el-option label="杭州" value="杭州" />
              <el-option label="深圳" value="深圳" />
              <el-option label="广州" value="广州" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="experienceFilter" placeholder="工作经验" clearable @change="handleFilter">
              <el-option label="全部" value="all" />
              <el-option label="应届生" value="应届生" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-5年" value="3-5年" />
              <el-option label="5年以上" value="5年以上" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 岗位列表 -->
      <div class="jobs-content" v-loading="loading">
        <div v-if="jobList.length > 0" class="jobs-list">
          <div
            v-for="job in jobList"
            :key="job.jobId"
            class="job-card"
          >
            <div class="job-card-header">
              <div class="job-title-section">
                <div class="job-title-row">
                  <h3 class="job-name">{{ job.jobName }}</h3>
                  <el-tag v-if="job.isTop" type="danger" size="small">置顶</el-tag>
                </div>
                <div class="job-salary" v-if="job.salary">
                  <span class="salary-text">{{ job.salary }}</span>
                </div>
              </div>
              <div class="enterprise-info" v-if="job.enterprise">
                <el-image
                  v-if="job.enterprise.imageUrl"
                  :src="getImageUrl(job.enterprise.imageUrl)"
                  class="enterprise-logo"
                  fit="cover"
                >
                  <template #error>
                    <div class="logo-placeholder">
                      <el-icon><OfficeBuilding /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="enterprise-name">{{ job.enterprise.enterpriseName }}</div>
              </div>
            </div>
            
            <div class="job-info-row">
              <span v-if="job.location" class="job-info-item">
                <el-icon><Location /></el-icon>
                {{ job.location }}
              </span>
              <span v-if="job.experience" class="job-info-item">
                <el-icon><Briefcase /></el-icon>
                {{ job.experience }}
              </span>
              <span v-if="job.education" class="job-info-item">
                <el-icon><School /></el-icon>
                {{ job.education }}
              </span>
              <span v-if="job.hiringCount" class="job-info-item">
                <el-icon><User /></el-icon>
                招聘 {{ job.hiringCount }} 人
              </span>
            </div>
            
            <div class="job-description" v-if="job.jobDescription">
              <p>{{ truncateText(job.jobDescription, 150) }}</p>
            </div>
            
            <div class="job-footer">
              <div class="job-footer-left">
                <span class="job-category" v-if="job.category">
                  <el-tag size="small">{{ job.category }}</el-tag>
                </span>
                <span class="job-time">{{ formatDate(job.createTime) }} 发布</span>
                <span class="job-views" v-if="job.viewCount">
                  <el-icon><View /></el-icon>
                  {{ job.viewCount }} 次浏览
                </span>
              </div>
              <div class="job-footer-right">
                <el-button 
                  size="small" 
                  :type="collectStatusMap.get(job.jobId) ? 'warning' : ''" 
                  :icon="collectStatusMap.get(job.jobId) ? StarFilled : Star" 
                  @click.stop="handleToggleCollect(job, $event)"
                >
                  {{ collectStatusMap.get(job.jobId) ? '已收藏' : '收藏' }}
                </el-button>
                <el-button type="primary" size="small" @click.stop="handleApply(job)">投递</el-button>
              </div>
            </div>
          </div>
        </div>
        
        <el-empty v-else description="暂无岗位信息" :image-size="200" />
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="jobList.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 投递对话框 -->
    <ApplyDialog
      v-model="applyDialogVisible"
      :job-id="currentJobId"
      @success="handleApplySuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Location, Briefcase, School, User, View, OfficeBuilding, Star, StarFilled } from '@element-plus/icons-vue'
import HomeNavBar from '@/components/HomeNavBar.vue'
import { jobAPI, collectJob, uncollectJob, checkJobCollected } from '@/api/enterprise'
import ApplyDialog from '@/components/job/ApplyDialog.vue'

const router = useRouter()

// 数据
const loading = ref(false)
const jobList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

// 收藏状态
const collectStatusMap = ref(new Map())

// 投递对话框
const applyDialogVisible = ref(false)
const currentJobId = ref(null)

// 筛选条件
const searchKeyword = ref('')
const categoryFilter = ref('all')
const locationFilter = ref('all')
const experienceFilter = ref('all')

// 获取岗位列表
const fetchJobList = async () => {
  loading.value = true
  try {
    const params = {
      keyword: searchKeyword.value || undefined,
      category: categoryFilter.value !== 'all' ? categoryFilter.value : undefined,
      location: locationFilter.value !== 'all' ? locationFilter.value : undefined,
      status: 'active', // 只显示招聘中的岗位
      page: currentPage.value,
      pageSize: pageSize.value
    }

    // 移除undefined的参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await jobAPI.getJobList(params)
    
    if (response.code === 0) {
      jobList.value = response.data.list || []
      total.value = response.data.total || 0
      // 获取收藏状态
      await fetchCollectStatus()
    } else {
      ElMessage.error(response.msg || '获取岗位列表失败')
      jobList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败，请重试')
    jobList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取收藏状态
const fetchCollectStatus = async () => {
  if (jobList.value.length === 0) return
  
  try {
    const statusChecks = jobList.value.map(job => 
      checkJobCollected(job.jobId).catch(() => ({ data: { isCollected: false } }))
    )
    const results = await Promise.all(statusChecks)
    
    const newMap = new Map()
    jobList.value.forEach((job, index) => {
      newMap.set(job.jobId, results[index]?.data?.isCollected || false)
    })
    collectStatusMap.value = newMap
  } catch (error) {
    console.error('获取收藏状态失败:', error)
  }
}

// 切换收藏状态
const handleToggleCollect = async (job, event) => {
  event.stopPropagation()
  
  const jobId = job.jobId
  const isCollected = collectStatusMap.value.get(jobId)
  
  try {
    if (isCollected) {
      await uncollectJob(jobId)
      // 创建新的 Map 以触发响应式更新
      const newMap = new Map(collectStatusMap.value)
      newMap.set(jobId, false)
      collectStatusMap.value = newMap
      ElMessage.success('取消收藏成功')
    } else {
      await collectJob(jobId)
      // 创建新的 Map 以触发响应式更新
      const newMap = new Map(collectStatusMap.value)
      newMap.set(jobId, true)
      collectStatusMap.value = newMap
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(isCollected ? '取消收藏失败' : '收藏失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchJobList()
}

// 筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchJobList()
}

// 重置
const handleReset = () => {
  searchKeyword.value = ''
  categoryFilter.value = 'all'
  locationFilter.value = 'all'
  experienceFilter.value = 'all'
  currentPage.value = 1
  fetchJobList()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchJobList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchJobList()
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `http://localhost:7001${url}`
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 处理投递
const handleApply = (job) => {
  currentJobId.value = job.jobId
  applyDialogVisible.value = true
}

// 投递成功回调
const handleApplySuccess = () => {
  // 可以刷新列表或显示提示
  ElMessage.success('投递成功')
}

// 初始化
onMounted(() => {
  fetchJobList()
})
</script>

<style lang="scss" scoped>
.job-list-page-wrapper {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.job-list-page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.jobs-content {
  min-height: 400px;
}

.jobs-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.job-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 24px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
    transform: translateY(-2px);
  }

  .job-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;

    .job-title-section {
      flex: 1;

      .job-title-row {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;

        .job-name {
          font-size: 20px;
          font-weight: 600;
          color: #303133;
          margin: 0;
        }
      }

      .job-salary {
        .salary-text {
          font-size: 18px;
          font-weight: 600;
          color: #f56c6c;
        }
      }
    }

    .enterprise-info {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-left: 20px;

      .enterprise-logo {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        overflow: hidden;
        flex-shrink: 0;

        .logo-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f0f0f0;
          color: #909399;
        }
      }

      .enterprise-name {
        font-weight: 500;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .job-info-row {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    margin-bottom: 12px;
    color: #909399;
    font-size: 14px;

    .job-info-item {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-icon {
        font-size: 16px;
      }
    }
  }

  .job-description {
    margin-bottom: 12px;

    p {
      margin: 0;
      color: #606266;
      line-height: 1.6;
      font-size: 14px;
    }
  }

  .job-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
    font-size: 13px;
    color: #909399;

    .job-footer-left {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .job-footer-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .job-views {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-icon {
        font-size: 14px;
      }
    }
  }
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

// 响应式
@media (max-width: 768px) {
  .job-card-header {
    flex-direction: column;
    
    .enterprise-info {
      margin-left: 0;
      margin-top: 12px;
    }
  }
}
</style>

